<template>
  <div class="dashboard-editor-container">
    <div class="top_panel">
      <el-row :gutter="12">
        <el-col :sm="2" :md="2" :lg="2">
          <span>总教室数:{{total}}</span>
        </el-col>
        <el-col :sm="6" :md="6" :lg="7" :offset="10">
          <el-input v-model="query.room" 
                    clearable 
                    placeholder="教室名称" 
                    @clear="getPage"
                    @keyup.enter.native="handleFilter" />
        </el-col>
        <el-col :sm="3" :md="3" :lg="2">
          <el-button type="info" icon="el-icon-search" @click="handleFilter">查找</el-button>
        </el-col>
        <el-col :sm="3" :md="3" :lg="3">
          <el-button type="primary" icon="el-icon-edit-outline" @click="createLab">创建教室</el-button>
        </el-col>
      </el-row>
    </div>
    
    <div class="lsit_content">
      <el-row :gutter="32">
        <el-col :xs="12" :sm="8" :lg="6" v-for="item in pageList" :key="item.rid">
          <room-item :room="item"></room-item>
        </el-col>
      </el-row>
    </div>
    
    
    
    <el-dialog title="申请表单" :visible.sync="dialogFormVisible">
      <el-form 
        ref="dataForm" 
        :rules="rules" 
        :model="temp" 
        size="small"
        label-position="right" 
        label-width="80px" 
        class="data-form">

        <el-form-item label="工号" prop="tid">
          <el-input v-model="temp.tid" readonly/>
        </el-form-item>
        <el-form-item label="名称" prop="title">
          <el-input v-model="temp.title" placeholder="输入课程名称"/>
        </el-form-item>
        <el-form-item label="班级" prop="cid">
          <el-input v-model.number="temp.cid" placeholder="输入班级号"/>
        </el-form-item>
        <el-form-item label="上传名单" prop="file">
          <el-upload
            ref="upload"
            :action="createRoom"
            :on-exceed="onExceed"
            :on-preview="onPreview"
            :on-success="onSuccess"
            :on-error="onError"
            :before-upload="beforeUpload"
            :headers="headers"
            :data="temp"
            :auto-upload="false"
            :limit="1"
            accept=".csv">
            <div slot="trigger" >
              <el-tooltip effect="light" placement="right">
                <div slot="content">
                  <div>内容格式示例如下：</div>
                  <img src="~@/assets/img/photos/example.png" width="180px"/>
                </div>
                <el-button size="small" type="primary" icon="el-icon-upload">选择文件</el-button>
              </el-tooltip>
            </div>
            <div slot="tip">上传csv文件，请勿超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="镜像" prop="imgId" placeholder="请选择">
          <el-select v-model="temp.imgId" class="filter-item" >
            <el-option v-for="item in imageList" :key="item.imgId" :label="item.imgName" :value="item.imgId" />
          </el-select>
        </el-form-item>
        <el-form-item label="截止至" prop="endTime">
          <el-date-picker v-model="temp.endTime" type="datetime" placeholder="设置使用期限"/>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.profile" 
                    :autosize="{ minRows: 2, maxRows: 4}" 
                    type="textarea" 
                    placeholder="在此输入具体描述" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
    
    <el-drawer
      :title="temp.title || 'CSV文件预览'"
      :visible.sync="drawer"
      :with-header="true">
        <el-table
          :data="csvContent"
          style="width: 100%">
          <el-table-column
            prop="0"
            :formatter="formatter">
          </el-table-column>
          <el-table-column
            prop="1"
            :formatter="formatter">
          </el-table-column>
        </el-table>
    </el-drawer>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import RoomItem from './components/RoomItem'
import { getImages } from '@/api/stack'
import { fetchRooms, createRoom } from '@/api/room'
import { mapGetters } from 'vuex'

export default {
  name: 'TeacherHome',
  components: { RoomItem },
  data() {
    return {
      fileList:[],
      createRoom,
      List: [],
      pageList:[],
      total: 0,
      query: {
        tid:null,
        room: null,
      },
      csvContent: '',
      drawer: false,
      dialogFormVisible: false,
      rules: {
        title: [{ required: true, message: '请填写申请的教室名称', trigger: 'blur' }],
        cid: [{required: true, message: '请填写申请的班级号', trigger: 'blur' },
              {type:'number',message: '请正确填写班级号'}],
        file: [{ required: false, message: '请上传申请名单', trigger: 'change'}],//fix here
        imgId: [{ required: true, message: '选择系统镜像', trigger: 'change'}],
        endTime:[{type:'date', required: true, message: '请选择截止日期', trigger: 'change' }]
      },
      imageList:[],
      temp: {
        tid: this.uid,
        title: '',
        cid: '',
        imgId: '',
        profile: '',
        endTime: null,
      },
    }
  },
  computed:{
    ...mapGetters([
      'uid',
      'role',
      'name',
    ]),
    headers() {
      return {
        'V-Token': getToken()
      }
    }
  },
  created() {
    this.query.tid = this.uid
    this.getList()
  },
  methods: {
    getList() {
      fetchRooms(this.query).then(response => {
        this.List = response.load.roomList
        this.total = response.load.total
        this.getPage()
      }).catch(()=>{
        console.log("获取教室列表失败")
      })
    },
    getPage(){
      this.pageList = this.List
    },
    resetTemp() {
      this.temp = {
        tid: this.uid,
        title: '',
        cid: '',
        imgId: '',
        profile: '',
        endTime: null,
      }
    },
    handleFilter() {
      if(this.query.room){
        this.pageList = this.List.filter(v=>v.name.indexOf(this.query.room) >= 0)
      }else{
        this.getPage()
      }
    },
    createLab(){
      //拉取实例模板列表用于显示，
      getImages(this.query).then(response => {
        this.imageList = response.load.imageList
        if(this.imageList.length > 0) {
          this.$nextTick(() => {//清除验证
            this.$refs['dataForm'].clearValidate()
          })
          this.resetTemp()
          this.dialogFormVisible = true
        }else{
          this.$message('暂无可用的实例模板，请联系管理员尽快处理。');
        }
      })
    },
    beforeUpload(file) {
      if (file.size / 1024 / 1024 > 10) {
        this.$message.error('上传文件大小不能超过10MB哦!')
        return false
      }
      if(file.name.replace(/.+\./,"") != 'csv') {
        this.$message.error('请上传csv文件!')
        return false
      }
    },
    onPreview(file) {
      let reader = new FileReader();
      reader.readAsText(file.raw,"utf-8");//发起异步请求
      reader.onload = e => {
        this.drawer = true
        let str = e.target.result
        this.csvContent = str.split("\r\n")
        this.csvContent.pop()
      }
    },
    formatter(row, column, cellValue, index){
      try{
        let arr = row.split(",")
        return arr[Number(column.property)]
      }catch{
        this.$message.error("文件格式错误！请检查是否有空行")
        this.$refs.upload.clearFiles()
      }
    },
    onExceed(files, fileList) {
      this.$message.warning(`当前限制选择1个文件，如需更改请先移除之前的文件！`)
    },
    onSuccess(res, file, fileList){
      this.$refs.upload.clearFiles()
      if (res.code !== 2000) {
        this.$message.error(res.msg || 'Error')
      }else{
        // this.dialogFormVisible = false//后台返回响应后关闭
        this.$notify({
          title: '成功',
          message: `成功创建虚拟教室。`,
          type: 'success',
          duration: 2000
        })
        this.getList()
      }
    },
    onError(err, file, fileList){
      console.log(err) // for debug
      this.$refs.upload.clearFiles()
      this.$message.error(err.messsage || 'Error')
    },
    submitForm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$refs.upload.submit()
          // console.log(this.temp,"teacer home")
          this.dialogFormVisible = false//点击提交之后直接关闭
          this.$notify({
            title: '成功',
            message: `表单成功提交至后台。`,
            type: 'success',
            duration: 2000
          })
        }
      })
      
    },
    cancelForm(){
      this.dialogFormVisible = false
      this.$refs.upload.abort()
    },
  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  // padding: 22px;
  .top_panel{
    margin-bottom: 20px;
    
    span{
      color: darkblue;
    }
  }
  .lsit_content{
    
  }
  .data-form{
    width: 70%;
    margin-left:50px;
  }
}

</style>
